package com.bluexmicro.ota2.ui.screen.facecustom

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.rememberAsyncImagePainter
import com.bluexmicro.ota2.picker.device.LaunchDevicePicker
import com.bluexmicro.ota2.picker.file.LaunchFilePicker
import com.bluexmicro.ota2.ui.custom.DisplayItem
import com.bluexmicro.ota2.ui.custom.ErrorDialog
import com.bluexmicro.ota2.ui.custom.KeepScreenOnView
import com.bluexmicro.ota2.ui.custom.TimeConsumingDialog
import com.bluexmicro.ota2.ui.custom.stepContent
import com.bluexmicro.ota2.ui.custom.stepTitle
import java.io.File

@SuppressLint("MissingPermission")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CustomFaceScreen(navHostController: NavHostController) {

    val viewModel: CustomFaceViewModel = viewModel()
    val context = LocalContext.current

    val image = remember {
        viewModel.image
    }

    val template = remember {
        viewModel.template
    }
    val target = remember {
        viewModel.target
    }
    val updating = remember {
        viewModel.updating
    }

    val canUpdate = remember {
        viewModel.canUpdate
    }

    var error by remember {
        viewModel.error
    }
    val progress = remember {
        derivedStateOf {
            (viewModel.progress.value * 100).toInt()
        }
    }

    var timeConsuming by remember {
        viewModel.timeConsuming
    }

    val cropper = rememberLauncherForActivityResult(contract = ImageCropper(), onResult = {
        viewModel.onPictureSelected(context, it)
    })

    val imagePicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.PickVisualMedia(),
        onResult = {
            if (it != null && template.value != null) {
                val temp = template.value!!
                cropper.launch(CropParam(it, temp.screenWidth, temp.screenHeight))
//                viewModel.onPictureSelected2(context, it)
            }
        }
    )

    val templatePicker =
        rememberLauncherForActivityResult(contract = LaunchFilePicker(), onResult = {
            if (it != null) {
                viewModel.unzipTemplate(context, it)
            }
        })

    val devicePicker =
        rememberLauncherForActivityResult(contract = LaunchDevicePicker(), onResult = {
            if (it != null) {
                viewModel.setTarget(it)
            }
        })

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(text = "自定义表盘")
                },
                colors = TopAppBarDefaults.smallTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = MaterialTheme.colorScheme.onPrimary,
                    navigationIconContentColor = MaterialTheme.colorScheme.onPrimary
                ),
                navigationIcon = {
                    IconButton(onClick = { navHostController.popBackStack() }) {
                        Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null)
                    }
                }
            )
        }
    ) {
        LazyColumn(
            modifier = Modifier.padding(it),
            contentPadding = PaddingValues(16.dp),
        ) {

            stepTitle(1, "选择模版文件", false)

            stepContent {

                template.value?.apply {
                    Text(
                        text = "模板大小：${templateRawData.size}字节\n裁剪后图片分辨率应为：${screenWidth}×${screenHeight}像素(px)",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onBackground.copy(0.5f),
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }

                Button(
                    onClick = {
                        templatePicker.launch("zip")
                    },
                    enabled = updating.value.not()
                ) {
                    Text(text = "选择")
                }
            }

            stepTitle(2, "选择目标图片并更改文字位置", false)
            stepContent {

                if (image.value != null && template.value != null) {
                    Image(
                        painter = rememberAsyncImagePainter(
                            image.value,
                            filterQuality = FilterQuality.High
                        ),
                        contentDescription = "background",
                        modifier = Modifier.size(
                            template.value!!.screenWidth.dp,
                            template.value!!.screenHeight.dp
                        ),
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }

                Button(
                    onClick = {
                        val req = PickVisualMediaRequest
                            .Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly)
                            .build()
                        imagePicker.launch(req)
                    },
                    enabled = template.value != null && updating.value.not()
                ) {
                    Text(text = "选择")
                }
            }

            stepTitle(3, "选择目标设备", false)
            stepContent {

                target.value?.let {
                    Card {
                        val name = if (TextUtils.isEmpty(it.device.name)) {
                            it.scanRecord?.deviceName ?: "N/A"
                        } else {
                            it.device.name
                        }
                        DisplayItem(title = name, desc = target.value?.device?.address ?: "未选择")
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                }

                Button(
                    onClick = {
                        devicePicker.launch(Unit)
                    },
                    enabled = updating.value.not()
                ) {
                    Text(text = "选择")
                }
            }


            val desc = if (updating.value) {
                if (progress.value == 0) {
                    ": 正在连接、初始化设备..."
                } else {
                    ": ${progress.value}%"
                }
            } else {
                ""
            }
            stepTitle(3, "升级$desc", canUpdate.value)
            stepContent {
                Button(
                    onClick = {
                        viewModel.startUpdate(context)
                    },
                    enabled = canUpdate.value
                ) {
                    Text(text = "开始升级")
                }
                KeepScreenOnView(keepOn = updating.value, modifier = Modifier.size(8.dp))
            }

        }
    }

    if (error != null) {
        ErrorDialog(error = error!!) {
            error = null
        }
    } else {
        if (timeConsuming != null) {
            TimeConsumingDialog(timeConsuming = timeConsuming!!) {
                timeConsuming = null
            }
        }
    }
}